<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/12/29
 * Time: 上午10:31
 */

namespace app\common;


class svn
{
	protected $usr = "";
	protected $pwd = "";
	protected $bin = "";

	public function __construct($usr = "", $pwd = "", $bin = "/usr/bin/svn")
	{
		$this->usr = $usr;
		$this->pwd = $pwd;
		$this->bin = $bin;
	}

	public function setUser($usr)
	{
		$this->usr = $usr;

		return $this;
	}

	public function setPwd($pwd)
	{
		$this->pwd = $pwd;

		return $this;
	}

	public function setBin($bin)
	{
		$this->bin = $bin;

		return $this;
	}

	public function run($action, $param, $xml = FALSE)
	{
		$cmd = escapeshellcmd($this->bin) . " " . $action . " " . $param . " --username $this->usr --password $this->pwd --no-auth-cache --non-interactive --trust-server-cert";
		if ($xml) {
			$cmd = $cmd . " --xml";
		}
		exec($cmd . " 2>&1", $output, $status);
		if ($status == 0) {
			return implode("\n", $output);
		} else {
			return FALSE;
		}
	}

	public function getChangeLog($url, $preRev, $curRev)
	{
		return $this->run("log", "-v -r $preRev:$curRev '$url'", TRUE);
	}

	public function getDiffLog($url, $preRev, $curRev, $mode = 0)
	{
		//如果$mode=0则是比较两个版本的差异，反之则比较指定版本和上一个版本的差异
		if (empty($mode)) {
			return $this->run("diff", "-r $preRev:$curRev '$url'");
		} else {
			return $this->run("diff", "-c $curRev '$url'");
		}
	}
}